package com.tian.web.admin.action;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.persistence.FetchType;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.json.annotations.JSON;

import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader.Array;
import com.tian.core.action.BaseAction;
import com.tian.core.entity.Group;
import com.tian.core.entity.Master;
import com.tian.core.entity.Mastergroup;
import com.tian.core.entity.Operbutton;
import com.tian.core.entity.Ztree;
import com.tian.core.entity.Ztreegroup;

@Namespace("/admin")
@Results( {  
	@Result(type = "dispatcher", name = "success", location = "/pages/admin/ztree.jsp"),
})
public class MenuAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	private String menu;
	
	@Override
	public String execute() throws Exception {
		//List<Actioncolumn> list = new ArrayList<Actioncolumn>();
		HttpSession session = ServletActionContext.getRequest().getSession();
		Master user = (Master)session.getAttribute("user");
		//需要取消懒加载，改为fetch = FetchType.EAGER
		List<Ztree> ztrees = new ArrayList<Ztree>();
		Set<Mastergroup> setMG = user.getMastergroups();
		Map buttonMap = new HashMap();
		for(Mastergroup mg : setMG){
			Group g = mg.getGroup();
			Set<Ztreegroup> zgs = g.getZtreegroups();
			//setZtrees.toArray()
			for(Ztreegroup zg : zgs){
				//List中的对象不能嵌套，如果嵌套的话，可能是转不了的 
				//加了@JSON(serialize = false)也没用
				Ztree ztree = zg.getZtree();
				ztree.setZtreegroups(null);
				List<Operbutton> buttonList = new ArrayList<Operbutton>();
				Set<Operbutton> setButtons = ztree.getOperbuttons();
				if(null != setButtons){
					for(Operbutton ob : setButtons){
						buttonList.add(ob);
					}
				}
				buttonMap.put(ztree.getName(), buttonList);
				ztree.setOperbuttons(null);
				ztrees.add(ztree);
			}
		}
		Collections.sort(ztrees);
		session.setAttribute("buttonMap", buttonMap);
		//List中的对象不能嵌套，如果嵌套的话，可能是转不了的 
		menu = JSONArray.fromObject(ztrees).toString();
		
		return SUCCESS;
	}

	public String getMenu() {
		return menu;
	}

	public void setMenu(String menu) {
		this.menu = menu;
	}
	
}

